import Card from '@/components/Card';
import Empty from '@/components/Empty';
import HandleBtn from '@/components/HandleBar/btn';
import { ModalForm, ProForm, ProFormSelect } from '@/components/Pro/';
import { stationAreaControllerImplListStationArea as getAreaList } from '@/services/ess/stationArea';
import {
  stationMainControllerFindMain as SvgData,
  stationMainControllerFindSvg as getSvg,
  stationMainControllerUpdateRefreshRate as setFreshRate,
  stationMainControllerUploadSvg as SvgUpload,
} from '@/services/ess/stationMain';
import type { UploadFile, UploadProps } from 'antd';
import { Flex, message, Modal, Upload } from 'antd';
import cls from 'classnames';
import React, { useEffect, useRef, useState } from 'react';
import { FullScreen, useFullScreenHandle } from 'react-full-screen';
import { getIntl, useIntl } from 'umi';
import styles from './index.less';
interface SvgDefsIdLgIds {
  id?: string;
  reallyuse?: string;
  lgIds?: string[];
}
type File = File | null;
const TableList: React.FC = () => {
  const [loading, setLoading] = useState(true);
  const [svgStr, setSvgStr] = useState('');
  const [isSetFrec, setisSetFrec] = useState(false);
  const [isSetArea, setisSetArea] = useState(false);
  const [isUpload, setisUpload] = useState(false);

  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [info, setFile] = useState<File>(null);
  const [createModalOpen, handleModalOpen] = useState<boolean>(false);
  const intl = useIntl();
  const elementRef = useRef(null);
  const [WiringData, setWiringData] = useState(new Map());
  const interTime = useRef<number>(30);
  const parid = useRef<number>();
  const [isHasSvgData, setisHasSvgData] = useState<boolean>(false);
  const handle = useFullScreenHandle();
  const { confirm } = Modal;
  const getIntlObject = getIntl();

  const IntervalTime = useRef(null);
  let sizeTimer: any = null; //窗口变化timer
  let allSvgDefsCopy: any = {};

  const [allSvgDefs, setallSvgDefs] = useState<object>({});

  const REFRESH_FREQUENCY = {
    30: {
      text: intl.formatMessage({
        id: 'global.30secondUnit',
      }),
    },
    60: {
      text: intl.formatMessage({
        id: 'global.60secondUnit',
      }),
    },
    90: {
      text: intl.formatMessage({
        id: 'global.90secondUnit',
      }),
    },
    120: {
      text: intl.formatMessage({
        id: 'global.120secondUnit',
      }),
    },
    300: {
      text: intl.formatMessage({
        id: 'global.5minuteUnit',
      }),
    },
    600: {
      text: intl.formatMessage({
        id: 'global.10minuteUnit',
      }),
    },
    900: {
      text: intl.formatMessage({
        id: 'global.15minuteUnit',
      }),
    },
    1200: {
      text: intl.formatMessage({
        id: 'global.20minuteUnit',
      }),
    },
    1800: {
      text: intl.formatMessage({
        id: 'global.30minuteUnit',
      }),
    },
  };

  const onRemove: UploadProps['onRemove'] = () => {
    setFileList([]);
  };

  const uploadImg: UploadProps = {
    name: 'file',
    fileList: fileList,
    listType: 'picture-card',
    onRemove: onRemove,
    maxCount: 1,
    accept: '.svg',
    multiple: false,
    customRequest: async (info) => {
      const isLt5M = info.file?.size / 1024 / 1024 < 5;
      if (!isLt5M) {
        message.error(
          getIntlObject.formatMessage({
            id: 'systemManagement.neddTochange.svgMax',
          }),
        );
        return;
      }
      setFile(info);
      setFileList([{ ...info.file, status: 'done' }]);
    },
  };

  const handleResize = () => {
    if (sizeTimer) {
      clearTimeout(sizeTimer);
    }
    sizeTimer = setTimeout(() => {
      if (elementRef.current) {
        console.log(elementRef.current);
        const width = elementRef?.current?.getBoundingClientRect().width;
        const height = elementRef?.current?.getBoundingClientRect().height;
        elementRef?.current?.querySelector('svg')?.setAttribute('width', width);
        elementRef?.current?.querySelector('svg')?.setAttribute('height', height);
        elementRef?.current?.querySelector('svg')?.setAttribute('viewBox', `0 0 2400 1300`);
      }
    }, 200);
  };

  const getLastCharStart = (char, str, end = false) => {
    const lastUnderscoreIndex = str.lastIndexOf(char);
    let result;
    if (lastUnderscoreIndex !== -1 && str.charAt(lastUnderscoreIndex + 1) !== char) {
      if (end) {
        result = str.substr(lastUnderscoreIndex + 1);
      } else {
        result = str.substr(0, lastUnderscoreIndex);
      }
    }
    return result;
  };

  const getUrlFromAttr = (attrVal) => {
    if (attrVal) {
      // url('#somegrad')
      if (attrVal.startsWith('url("')) {
        return attrVal.substring(5, attrVal.indexOf('"', 6));
      }
      // url('#somegrad')
      if (attrVal.startsWith("url('")) {
        return attrVal.substring(5, attrVal.indexOf("'", 6));
      }
      if (attrVal.startsWith('url(')) {
        return attrVal.substring(4, attrVal.indexOf(')'));
      }
    }
    return null;
  };

  const getUrlLink = (links, elem) => {
    let fill_attrVal = elem.getAttribute('fill');
    let fill_link = getUrlFromAttr(fill_attrVal);
    if (fill_link) {
      links.push(fill_link);
    }

    let stroke_attrVal = elem.getAttribute('stroke');
    let stroke_link = getUrlFromAttr(stroke_attrVal);
    if (stroke_link) {
      links.push(stroke_link);
    }
  };

  const ToallSvgDefs = (svgDoc) => {
    allSvgDefsCopy = {};
    let svgDefs = svgDoc.querySelector('defs').children;
    for (let i = 0; i < svgDefs.length; i++) {
      let defid = '#' + svgDefs[i].getAttribute('del');
      if (defid === '#null') {
        continue;
      }
      defid = getLastCharStart('_', defid);
      if (!allSvgDefsCopy[defid]) {
        allSvgDefsCopy[defid] = [];
      }

      let svgDefsId_lgIds: SvgDefsIdLgIds = {};
      svgDefsId_lgIds.id = '#' + svgDefs[i].getAttribute('id');
      svgDefsId_lgIds.reallyuse = getLastCharStart('_', svgDefs[i].getAttribute('del'), true);
      let linearGradientIds: string[] = [];
      for (let j = 0; j < svgDefs[i].children.length; j++) {
        getUrlLink(linearGradientIds, svgDefs[i].children[j]);
      }
      if (linearGradientIds.length > 0) {
        svgDefsId_lgIds.lgIds = linearGradientIds;
      }
      allSvgDefsCopy[defid].push(svgDefsId_lgIds);
    }

    setallSvgDefs(allSvgDefsCopy);
  };

  const initDate = (result) => {
    const updateFunction = async () => {
      let obj = [...(result?.data?.ycData?.data || []), ...(result?.data?.yxData?.data || [])];
      // 使用Map对象存储数据
      const mapOBJ = new Map();
      obj.forEach((item) => {
        if (mapOBJ.has(item.id)) {
          console.log(`重复键: ${item.id}`);
        }
        mapOBJ.set(item.id, { ...item, val: item?.val || null });
      });
      setWiringData(mapOBJ);
    };

    updateFunction();
  };

  const initSvg = (svgStr: string | undefined) => {
    if (elementRef.current) {
      const width = elementRef?.current?.getBoundingClientRect().width;
      const height = elementRef?.current?.getBoundingClientRect().height;
      const parser = new DOMParser();
      let svgDoc = parser.parseFromString(svgStr, 'image/svg+xml');
      const title = svgDoc.querySelector('.layer > title'); // 选择.layer下的第一个子元素title
      if (title) {
        title.remove(); // 将选中的title元素从DOM中移除
      }
      svgDoc.querySelector('svg')?.setAttribute('width', width);
      svgDoc.querySelector('svg')?.setAttribute('height', height);

      // svgDoc.querySelector('.layer')?.setAttribute('width', width);
      // svgDoc.querySelector('.layer')?.setAttribute('height', height);
      svgDoc.querySelector('svg')?.setAttribute('viewBox', `0 0 2400 1300`);
      ToallSvgDefs(svgDoc);
      const updatedSvgString = new XMLSerializer().serializeToString(svgDoc);
      return updatedSvgString;
    }
  };

  //初始化svg相应方法
  const initSvgData = async () => {
    try {
      const res = await getSvg({
        areaId: parid?.current ?? undefined,
      });
      if (res?.data && res?.data !== '') {
        setLoading(false);
        setisHasSvgData(true);
        const response = await fetch(res.data);

        if (response.ok) {
          const svgString = await response.text();
          let str = initSvg(svgString);
          setSvgStr(str);
          const svgDataRes = await SvgData({ areaId: parid?.current ?? undefined });
          if (svgDataRes.success) {
            initDate(svgDataRes);
            interTime.current = Number(svgDataRes?.data?.period) || 30;
          } else {
            setLoading(false);
          }

          window.addEventListener('resize', handleResize);
          return () => {
            window.removeEventListener('resize', handleResize);
          };
        }
      } else {
        setLoading(false);
        setisHasSvgData(false);
      }
    } catch (error) {
      setisHasSvgData(false);
      console.error('Error fetching the SVG:', error);
    }
  };

  useEffect(() => {
    getAreaList().then((res) => {
      if (res?.data && res.data.length) {
        parid.current = res.data[0].id;
      }
      initSvgData();
    });
  }, []);

  useEffect(() => {
    const fetchData = async () => {
      let result = await SvgData({
        areaId: parid?.current ?? undefined,
      });
      let obj = [...(result?.data?.ycData?.data || []), ...(result?.data?.yxData?.data || [])];
      const mapOBJ = new Map();
      obj.forEach((item) => {
        if (mapOBJ.has(item.id)) {
          console.log(`重复键: ${item.id}`);
        }
        mapOBJ.set(item.id, { ...item, val: item?.val || null });
      });
      setWiringData(mapOBJ);
    };

    fetchData(); // 立即执行一次更新频率后直接更新视图

    IntervalTime.current = setInterval(fetchData, interTime.current * 1000);

    return () => {
      if (IntervalTime.current) {
        clearInterval(IntervalTime.current);
      }
    };
  }, [interTime.current, parid.current]); // 当interTime.current改变时重新设置定时器

  useEffect(() => {
    //dom数据更新
    if (WiringData && WiringData.size && Object.keys(allSvgDefs).length > 0) {
      const parser = new DOMParser();
      const svgDoc = parser.parseFromString(svgStr, 'image/svg+xml');
      // 找到id与map对象中的键名相同的g元素，并且doc-type属性为"barry"
      const gs = svgDoc.querySelectorAll('g');

      gs.forEach((g) => {
        const id = g.getAttribute('id');
        if (WiringData?.has(id) && g.classList.contains('ems')) {
          //动态数据类处理
          if (g.getAttribute('doc-type') === 'datatext') {
            const textElement = g.querySelector('text');
            if (textElement) {
              if (WiringData.get(id)?.val !== null) {
                textElement.textContent = WiringData.get(id)?.val;
              }
            }
          }

          //barry类图元处理
          if (g.getAttribute('doc-type') === 'barry') {
            let idBattary = `#${id}_text`;
            let defsId = 'lg_barry_' + `${id}`;
            const textElement = svgDoc.querySelector(idBattary);
            if (textElement) {
              if (WiringData.get(id)?.val !== null) {
                textElement.textContent = WiringData.get(id)?.val + '%';
                let val: number = Number(Math.floor(100 - parseFloat(WiringData.get(id)?.val)));
                if (!isNaN(val)) {
                  svgDoc.querySelector(`#${defsId}`)?.setAttribute('y1', val / 100 + 0.01);
                  svgDoc.querySelector(`#${defsId}`)?.setAttribute('y2', val / 100);
                }
              }
            }
          }

          //KG类图元处理
          if (g.getAttribute('doc-type') === 'KG') {
            let use = g.querySelector('use');
            if (use && use.getAttribute('xlink:href')) {
              let url = getLastCharStart('_', use.getAttribute('xlink:href'));
              let defs = allSvgDefs[url];
              if (defs && defs.length > 1) {
                if (WiringData.get(id)?.val === 'true' || WiringData.get(id)?.val === 'H') {
                  use.setAttribute(
                    'xlink:href',
                    defs?.filter((res) => res.reallyuse === '合')?.[0]?.['id'] || defs[0]['id'],
                  );
                } else {
                  use.setAttribute(
                    'xlink:href',
                    defs?.filter((res) => res.reallyuse === '分')?.[0]?.['id'] || defs[1]['id'],
                  );
                }
              }

              if (WiringData.get(id)?.hand !== null) {
                if (
                  g.getAttribute('doc-type') === 'KG' &&
                  g.getAttribute('title') &&
                  g.getAttribute('title') !== WiringData.get(id)?.val
                ) {
                  //如果有开关遥信变位，保留现场
                  g.setAttribute('close', 'true');

                  use.setAttribute(
                    'xlink:href',
                    defs?.filter((res) => res.reallyuse === '其它')?.[0]?.['id'] || defs?.[2]['id'],
                  );
                }
              }
            }
            if (WiringData.get(id)?.set) {
              g.setAttribute('close', WiringData.get(id)?.val);
            }
          }

          //其它类图元处理
          if (g.getAttribute('doc-type') === 'QT') {
            let use = g.querySelector('use');

            let url = getLastCharStart('_', use.getAttribute('xlink:href'));
            // let url = use.getAttribute("xlink:href").split("_")[0]

            let defs = allSvgDefs[url];
            if (defs && defs.length > 1) {
              if (
                WiringData.get(id)?.val !== null &&
                WiringData.get(id)?.val !== '其他' &&
                !isNaN(parseInt(WiringData.get(id)?.val))
              ) {
                let arr = defs.map((res) => res.reallyuse);
                if (arr.includes(String(parseInt(WiringData.get(id)?.val)))) {
                  use.setAttribute('xlink:href', url + '_' + parseInt(WiringData.get(id)?.val));
                } else {
                  use.setAttribute('xlink:href', url + '_其他');
                }
              } else {
                use.setAttribute('xlink:href', url + '_其他');
              }
            }
          }
        }
      });

      // 将更新后的svg字符串返回给React组件进行渲染
      const updatedSvgString = new XMLSerializer().serializeToString(svgDoc);
      setSvgStr(updatedSvgString);
    }
  }, [WiringData]);

  return (
    <div className={styles.wrap}>
      <Card
        bodyStyle={{ paddingTop: 15, paddingBottom: 15 }}
        loading={loading}
        title={
          <span>
            {intl.formatMessage({
              id: 'remoteUpgradeMangment.mainWiringDiagram.mainWiringDiagram',
            })}
          </span>
        }
        extra={
          <div>
            <HandleBtn
              handleType="enlarg"
              onClick={() => {
                handle.enter();
                handleResize();
              }}
            >
              {intl.formatMessage({ id: 'remoteUpgradeMangment.other.fullScreen' })}
            </HandleBtn>

            {parid?.current ? (
              <HandleBtn
                handleType="parameter"
                onClick={() => {
                  setisSetArea(true);
                  setisSetFrec(false);
                  setisUpload(false);
                  handleModalOpen(true);
                }}
              >
                {intl.formatMessage({
                  id: 'remoteUpgradeMangment.mainWiringDiagram.refreshAreaSetting',
                })}
              </HandleBtn>
            ) : null}
            <HandleBtn
              handleType="parameter"
              onClick={() => {
                setisSetArea(false);
                setisSetFrec(true);
                setisUpload(false);
                handleModalOpen(true);
              }}
            >
              {intl.formatMessage({
                id: 'remoteUpgradeMangment.mainWiringDiagram.refreshFrequencySetting',
              })}
            </HandleBtn>
            <HandleBtn
              handleType="import"
              onClick={() => {
                setFileList([]);
                setisSetArea(false);
                setisSetFrec(false);
                setisUpload(true);
                handleModalOpen(true);
              }}
            >
              {intl.formatMessage({ id: 'remoteUpgradeMangment.mainWiringDiagram.import' })}
            </HandleBtn>
          </div>
        }
        style={{ marginTop: 20, minHeight: 200 }}
        hasHeaderBorder={true}
      >
        <FullScreen handle={handle}>
          <div
            ref={elementRef}
            className={cls([styles['svgWrap']], {
              [styles['active']]: handle.active,
            })}
          >
            {isHasSvgData ? (
              <div dangerouslySetInnerHTML={{ __html: svgStr }} className={styles.svgContent}></div>
            ) : (
              <Flex justify="center" style={{ width: '100%', height: 'calc(100vh - 250px)' }}>
                <Empty />
              </Flex>
            )}
          </div>
        </FullScreen>
      </Card>

      <ModalForm
        open={createModalOpen}
        modalProps={{
          destroyOnClose: true,
          onCancel: () => {
            setFileList([]);
            setisSetArea(false);
            setisSetFrec(false);
            setisUpload(false);
            handleModalOpen(false);
          }, // 点击取消按钮或者关闭按钮时调用
        }}
        initialValues={{ seconds: String(interTime.current), areaId: parid.current }}
        width={835}
        colProps={{ md: 12 }}
        onFinish={async (value) => {
          if (isSetFrec) {
            let params = {
              seconds: String(value?.seconds),
              areaId: parid?.current ?? undefined,
            };
            try {
              let reslut = await setFreshRate(params);
              if (reslut.success) {
                interTime.current = Number(value?.seconds);
              }
            } catch (error) {
              console.log(error);
            }
            setisSetFrec(false);
            handleModalOpen(false);
          } else if (isSetArea) {
            parid.current = value?.areaId;
            initSvgData();
            setisSetArea(false);
            handleModalOpen(false);
          } else if (isUpload) {
            try {
              let reslut = await getSvg({
                areaId: parid?.current ?? undefined,
              });
              if (reslut.success && reslut.data && reslut.data !== '') {
                confirm({
                  title: intl.formatMessage({ id: 'login.prompt' }),
                  content: intl.formatMessage({
                    id: 'remoteUpgradeMangment.mainWiringDiagram.tipSvgReapeat',
                  }),
                  onOk: async () => {
                    const res = await SvgUpload(
                      {
                        areaId: parid?.current ?? undefined,
                      },
                      {},
                      info.file,
                    );
                    if (res?.success) {
                      message.success(
                        `${info.file.name} ${intl.formatMessage({
                          id: 'remoteUpgradeMangment.mainWiringDiagram.svgUploadSuccess',
                        })}`,
                      );
                      initSvgData();
                      setisUpload(false);
                      handleModalOpen(false);
                      // return info.file;
                    } else {
                      const msg = info?.file?.response?.message;
                      message.error(
                        `${info.file.name} ${intl.formatMessage({
                          id: 'remoteUpgradeMangment.mainWiringDiagram.svgUploadFailad',
                        })} ${msg ? ',' + msg : ''}`,
                      );
                      setFileList([]);
                    }
                  },
                  onCancel: () => {
                    setisUpload(false);
                    handleModalOpen(false);
                  },
                });
              } else {
                const res = await SvgUpload(
                  {
                    areaId: parid?.current ?? undefined,
                  },
                  {},
                  info.file,
                );
                if (res?.success) {
                  message.success(
                    `${info.file.name} ${intl.formatMessage({
                      id: 'remoteUpgradeMangment.mainWiringDiagram.svgUploadSuccess',
                    })}`,
                  );
                  initSvgData();
                  setisUpload(false);
                  handleModalOpen(false);
                  // return info.file;
                } else {
                  const msg = info?.file?.response?.message;
                  message.error(
                    `${info.file.name} ${intl.formatMessage({
                      id: 'remoteUpgradeMangment.mainWiringDiagram.svgUploadFailad',
                    })} ${msg ? ',' + msg : ''}`,
                  );
                  setFileList([]);
                  setisUpload(false);
                  handleModalOpen(false);
                }
              }
            } catch (error) {
              console.log(error, 'fdjslfjdlsjfdkljfdskljdfsklfj');
            }
          }
        }}
      >
        {!isSetFrec || isSetArea || isUpload ? (
          isUpload ? (
            <ProForm.Item
              name="pictureDir"
              label={intl.formatMessage({ id: 'remoteUpgradeMangment.generalProcedure.uploadSvg' })}
              style={{ width: '100%' }}
              tooltip={getIntlObject.formatMessage({
                id: 'systemManagement.neddTochange.svgFormatSupport',
              })}
              rules={[
                {
                  required: true,
                  message: getIntlObject.formatMessage({
                    id: 'systemManagement.neddTochange.svgMust',
                  }),
                },
                () => ({
                  validator(_, value) {
                    if (!value) {
                      return Promise.resolve();
                    }
                    if (value?.file?.status === 'done' || value?.file?.status === 'uploading') {
                      return Promise.resolve();
                    }
                    return Promise.reject(
                      intl.formatMessage({
                        id: 'remoteUpgradeMangment.mainWiringDiagram.svgrequire',
                      }),
                    );
                  },
                }),
              ]}
            >
              <Upload {...uploadImg}>
                {fileList.length < 1 && (
                  <span>
                    {intl.formatMessage({ id: 'remoteUpgradeMangment.generalProcedure.upload' })}
                  </span>
                )}
              </Upload>
            </ProForm.Item>
          ) : (
            isSetArea && (
              <ProFormSelect
                name="areaId"
                label={intl.formatMessage({
                  id: 'remoteUpgradeMangment.mainWiringDiagram.area',
                })}
                request={async () => {
                  let reslut = await getAreaList();

                  return (
                    reslut?.data.map((res) => {
                      return {
                        value: res.id,
                        label: res.areaName,
                      };
                    }) || []
                  );
                }}
              />
            )
          )
        ) : (
          <ProFormSelect
            name="seconds"
            label={intl.formatMessage({
              id: 'remoteUpgradeMangment.mainWiringDiagram.refreshCycle',
            })}
            valueEnum={REFRESH_FREQUENCY}
            rules={[
              {
                required: true,
                message: intl.formatMessage({
                  id: 'remoteUpgradeMangment.mainWiringDiagram.refreshCycleRequire',
                }),
              },
            ]}
          />
        )}
      </ModalForm>
    </div>
  );
};
export default TableList;
